/*
 * @Description: 密码\token验证
 * @Author: pinus
 * @Email: pinus0716@163.com
 * @Git: https://gitee.com/xyf97
 * @Date: 2021-10-07 11:46:13
 * @LastEditTime: 2021-10-08 16:50:33
 */

const passport = require('passport')
const LocalStrategy = require('passport-local').Strategy
const Strategy = require('passport-http-bearer').Strategy
const jwt = require('jsonwebtoken')
const jwt_config = require('config').get('jwt_config')
const _ = require('lodash')

/**
 * @description: 初始化 passport 框架
 * @param {*} app       - 全局应用程序
 * @param {*} loginFunc - 登录函数
 * @param {Function} callback
 * @return {*}
 */
module.exports.setup = function (app, loginFunc, callback) {
  // 用户名密码登录策略
  passport.use(
    new LocalStrategy(function (username, password, done) {
      if (!loginFunc) return callback('未设置登陆验证函数')

      loginFunc(username, password, (err, user) => {
        if (err) return done(err)
        return done(null, user)
      })
    })
  )

  // token 验证策略
  passport.use(
    new Strategy(function (token, done) {
      jwt.verify(token, jwt_config.get('secretKey'), function (err, decode) {
        if (err) {
          return done('验证错误')
        }
        return done(null, decode)
      })
    })
  )

  // 初始化passport模块
  app.use(passport.initialize())

  if (callback) callback()
}

/**
 * @description: 登录验证逻辑
 * @param {*} req
 * @param {*} res
 * @param {*} next
 * @return {*}
 */
module.exports.login = function (req, res, next) {
  passport.authenticate('local', function (err, user, info) {
    console.log(err)
    if (err) return res.sendResult(null, 400, err)
    if (!user) return res.sendResult(null, 400, '参数错误')

    // 获取角色信息
    var token = jwt.sign({ uid: user.id, rid: user.rid }, jwt_config.get('secretKey'), { expiresIn: jwt_config.get('expiresIn') })
    user.token = 'Bearer ' + token
    return res.sendResult(user, 200, '登录成功')
  })(req, res, next)
}

/**
 * @description: token验证函数
 * @param {*} req
 * @param {*} res
 * @param {*} next
 * @return {*}
 */
module.exports.tokenAuth = function (req, res, next) {
  passport.authenticate('bearer', { session: false }, function (err, tokenData) {
    if (err) return res.sendResult(null, 400, '无效token')
    if (!tokenData) return res.sendResult(null, 400, '无效token')
    req.userInfo = {}
    req.userInfo.uid = tokenData['uid']
    req.userInfo.rid = tokenData['rid']
    next()
  })(req, res, next)
}
